#include "WidgetVariantBool.h"
#include "EVariant.h"
#include <ECommand.h>
#include "ui_WidgetVariantBool.h"

WidgetVariantBool::WidgetVariantBool(QWidget *parent) :
    WidgetVariant(parent),
    ui(new Ui::WidgetVariantBool)
{
    ui->setupUi(this);
}

WidgetVariantBool::~WidgetVariantBool()
{
    delete ui;
}

// void WidgetVariantBool::setDisplayName(const QString& name)
// {
    // ui->labelName->setText(name);
// }

void WidgetVariantBool::refreshByProperty(EItemMetaPropertyPtr p)
{
    WidgetVariant::refreshByProperty(p);
    this->clearConnect();

    EString text = p->nameCN.isEmpty() ? p->name : p->nameCN;
    if(text.left(3) == "ui_")
    {
        text.removeLeft(3);
    }
    ui->labelName->setText(text.data());

    p->getPropertyValue(p->value);

    ui->checkBox->setChecked(p->value.to_bool());

    ui->checkBox->setEnabled(!p->ifReadOnly);

    this->buildConnect();
}

void WidgetVariantBool::buildConnect()
{
    QObject::connect(ui->checkBox, SIGNAL(stateChanged(int)),
                     this, SLOT(slotCheckBoxStateChanged(int)));
}

void WidgetVariantBool::clearConnect()
{
    QObject::disconnect(ui->checkBox, SIGNAL(stateChanged(int)),
                     this, SLOT(slotCheckBoxStateChanged(int)));
}

void WidgetVariantBool::slotCheckBoxStateChanged(int state)
{
    // if (m_property == nullptr)
    // {
        // return;
    // }

    // m_property->name = ui->labelName->text();
    // m_property->typeName = "bool";

    bool uiVlaue = false;
    if(state == Qt::CheckState::Unchecked)
    {
        uiVlaue = false;
    }
    else if(state == Qt::CheckState::Checked)
    {
        uiVlaue = true;
    }

    EVariant varOld = this->m_property->value;
    EVariant var(uiVlaue);
    this->m_property->setPropertyValue(var);

    emit signalVariantChanged(this->m_property, varOld);
}
